package org.jeecg.modules.activiti.listener;

import com.alibaba.fastjson.JSON;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.activiti.entity.ActBusiness;
import org.jeecg.modules.activiti.service.IActBusinessService;
import org.jeecg.modules.activiti.service.IActZprocessService;
import org.jeecg.modules.putstorage.entity.ZcglPutStorage;
import org.jeecg.modules.putstorage.entity.ZcglPutStorageAssets;
import org.jeecg.modules.putstorage.service.IZcglPutStorageAssetsService;
import org.jeecg.modules.putstorage.vo.ZcglPutStoragePage;
import org.jeecg.modules.zcgl.entity.AssetFixed;
import org.jeecg.modules.zcgl.service.IAssetFixedService;
import org.jeecg.modules.zcgl.vo.AssetInfoPage;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PutStorageAssetsListener  implements ExecutionListener {

    IActBusinessService actBusinessService;
    IAssetFixedService assetFixedService;

    IZcglPutStorageAssetsService zcglPutStorageAssetsService;


    @Override
    public void notify(DelegateExecution execution) throws Exception {
        if (actBusinessService == null) {
            actBusinessService = (IActBusinessService) SpringContextUtils.getBean("actBusinessServiceImpl");
        }
        if (zcglPutStorageAssetsService == null) {
            zcglPutStorageAssetsService = (IZcglPutStorageAssetsService) SpringContextUtils.getBean("zcglPutStorageAssetsServiceImpl");
        }
        if (assetFixedService == null) {
            assetFixedService = (IAssetFixedService) SpringContextUtils.getBean("assetFixedServiceImpl");
        }
        String eventName = execution.getEventName();
        //start
        if (EVENTNAME_START.equals(eventName)) {

        } else if (EVENTNAME_END.equals(eventName)) {
            ActBusiness actBusiness = actBusinessService.getById(execution.getProcessBusinessKey());
            if (actBusiness != null && "zcgl_put_storage".equalsIgnoreCase(actBusiness.getTableName())){
                ZcglPutStoragePage page = JSON.parseObject(actBusiness.getData(), ZcglPutStoragePage.class);

                List<ZcglPutStorageAssets> list = page.getZcglPutStorageAssetsList();

                for (int i = 0; i < list.size(); i++) {
                    ZcglPutStorageAssets zcglPutStorageAssets = list.get(i);
                    AssetFixed assetFixed = assetFixedService.getById(zcglPutStorageAssets.getAssetId());
                    assetFixed.setAmount(assetFixed.getAmount().subtract(zcglPutStorageAssets.getAssetAmount()));
                    assetFixedService.updateById(assetFixed);
                }
            }
        }

    }
}
